package utils
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.managers.PopUpManager;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import ui.notifications.BusyNotification;
	import ui.notifications.ErrorNotification;

	public class BlockingHTTPService extends HTTPService
	{
		/**
		 * @public
		 * How much time is allowed to wait before showing the buzy box
		 */
		public var waitingTime:Number = 1000;
		private var timer:Timer;
		
		private var busyWindow:BusyNotification = null;
		private var errorWindow:ErrorNotification = null;
		
		[Bindable]
		public var busyText:String = "Communicating with server...";
		
		public function BlockingHTTPService(rootURL:String=null, destination:String=null)
		{
			super(rootURL, destination);
			
			
			addEventListener(ResultEvent.RESULT, onResult);
			addEventListener(FaultEvent.FAULT, onFault);
		}
		
		private function onWaitingTimeExpired(evt:TimerEvent):void{
			timer.stop();
			
			if(Config.lockGUIWhileRecord){
				busyWindow = new BusyNotification();
				busyWindow.text = busyText;
				busyWindow.popUp();
			}
		}
		
		private function onResult(evt:ResultEvent):void{
			timer.stop();
			closeAllWindows();
		}
		
		private function onFault(evt:FaultEvent):void{
			timer.stop();
			closeAllWindows();
			
			errorWindow = new ErrorNotification();
			errorWindow.text = "An error occured while trying to reach server";
			errorWindow.popUp();
		}
		
		private function closeAllWindows():void{
			if(!Config.lockGUIWhileRecord)
				return;
			
			if(busyWindow){
				busyWindow.close();
				busyWindow = null;
			}
			
			if(errorWindow){
				errorWindow.close();
				errorWindow = null;
			}
		}
		
		override public function send(parameters:Object=null):AsyncToken{
			timer = new Timer(waitingTime, 1);
			timer.addEventListener(TimerEvent.TIMER, onWaitingTimeExpired);
			
			timer.start();
			
			return super.send(parameters);
		}
		
		private function dummy(evt:Event = null):void{
		}
		
	}
}